package com.red.servlet;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.red.connetcion.Result;
import com.red.controller.UserController;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Objects;


@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    private final UserController userController = new UserController();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("u:"+username);
        System.out.println("p:"+password);
        if (StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            Result fail = Result.fail("请输入内容");
            String jsonStr = JSONUtil.toJsonStr(fail);
            response.getWriter().write(jsonStr);
//            response.setStatus(401);
            request.getSession().invalidate();
            return;
        }
        Result result = userController.login(username, password);
        if (Objects.isNull(result)){
            Result fail = Result.fail("系统错误");
            String jsonStr = JSONUtil.toJsonStr(fail);
            response.getWriter().write(jsonStr);
            request.getSession().removeAttribute("loginInfo");
//            response.getWriter().write("<script>alert(\"系统错误\");location.href = \"login.jsp\";</script>");
            return;
        }
        if (result.getSuccess()){
            request.getSession().setAttribute("loginInfo",result);
            Result ok = Result.ok(result, "登陆成功");
            String jsonStr = JSONUtil.toJsonStr(ok);
            response.getWriter().write(jsonStr);
//            response.getWriter().write("<script>alert(\"登陆成功\");location.href = \"index.jsp\";</script>");
        }else{
            Result fail = Result.fail("密码错误");
            request.getSession().removeAttribute("loginInfo");
            response.getWriter().write(JSONUtil.toJsonStr(fail));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
